package com.itheima.springbootwebtlias.service.Impl;

import com.itheima.springbootwebtlias.anno.LogOperation;
import com.itheima.springbootwebtlias.anno.MyLog;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.DeptMapper;
import com.itheima.springbootwebtlias.mapper.EmpMapper;
import com.itheima.springbootwebtlias.pojo.Dept;
import com.itheima.springbootwebtlias.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    //查询所有部门列表的业务功能方法

    @Override
    public List<Dept> selectAll() {
       //1.调用持久层Mapper,查询部门列表
        List<Dept> depts = deptMapper.selectAll();
        //返回查询列表
        return depts;
    }

    //根据id删除部门
    @MyLog
    @Override
    @LogOperation
    public void removeById(Integer id) {

        //0.查询当前部门下是否存在员工
        //1.如果存在员工，不允许删除
        Integer count = empMapper.selectByDeptId(id);
        if(count != 0){
            //不允许删除,存在员工
            throw new DeletionIsNotAllowed("当前部门存在员工，不允许删除");
        }
        
        //1.调用持久层Mapper 删除指定部门
        deptMapper.removeById(id);
    }

    //添加部门
    @Override
    @LogOperation
    public void saveDept(Dept dept) {
        //1.补充基础信息：创建时间、更新时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //2.调用持久层Mapper,保存部门
        deptMapper.saveDept(dept);
    }

    //查询指定部门
    @Override
    public Dept findById(int id) {
        //1.调用持久层Mapper,查询指定部门
        return deptMapper.selectById(id);

    }

    //更新部门业务功能方法
    @Override
    @LogOperation
    public void update(Dept dept) {
        //1.同步更新时间
        dept.setUpdateTime(LocalDateTime.now());

        //2.调用持久层Mapper,更新部门
        deptMapper.update(dept);
    }
}
